package com.xqb.modules.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xqb.common.constant.CacheConstants;
import com.xqb.common.constant.Constants;
import com.xqb.common.core.redis.RedisCache;
import com.xqb.common.utils.DateUtils;
import com.xqb.common.utils.bean.BeanUtils;
import com.xqb.modules.domain.dto.LesCatalogueListDto;
import com.xqb.modules.domain.po.ExaQuestionBiz;
import com.xqb.modules.domain.po.LesCourse;
import com.xqb.modules.domain.po.LesCourseCatalogue;
import com.xqb.modules.domain.vo.LesAllCatalogueVo;
import com.xqb.modules.domain.vo.SectionVO;
import com.xqb.modules.mapper.ExaQuestionBizMapper;
import com.xqb.modules.mapper.LesCourseCatalogueMapper;
import com.xqb.modules.mapper.LesCourseMapper;
import com.xqb.modules.service.ILesCourseCatalogueService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 课程目录Service业务层处理
 *
 * @author xqb
 * @date 2024-10-14
 */
@Service
@Slf4j
public class LesCourseCatalogueServiceImpl implements ILesCourseCatalogueService {
    @Autowired
    private LesCourseCatalogueMapper lesCourseCatalogueMapper;
    @Autowired
    private LesCourseMapper lesCourseMapper;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private ExaQuestionBizMapper exaQuestionBizMapper;

    /**
     * 查询课程目录
     *
     * @param id 课程目录主键
     * @return 课程目录
     */
    @Override
    public LesCourseCatalogue selectLesCourseCatalogueById(Long id) {
        return lesCourseCatalogueMapper.selectLesCourseCatalogueById(id);
    }

    /**
     * 查询课程目录列表
     *
     * @param lesCourseCatalogue 课程目录
     * @return 课程目录
     */
    @Override
    public List<LesCourseCatalogue> selectLesCourseCatalogueList(LesCourseCatalogue lesCourseCatalogue) {
        List<LesCourseCatalogue> lesCourseCatalogues;
        //递归遍历构建树形结构
        if (redisCache.hasKey(CacheConstants.CATALOGUE_KEY)) {
            log.info("从缓存中获取课程目录");
            lesCourseCatalogues = redisCache.getCacheObject(CacheConstants.CATALOGUE_KEY);
        } else {
            QueryWrapper<LesCourseCatalogue> queryWrapper = new QueryWrapper<>();
            queryWrapper.orderByAsc("c_index");
            lesCourseCatalogues = lesCourseCatalogueMapper.selectLesCourseCatalogueList(lesCourseCatalogue);
            redisCache.setCacheObject(CacheConstants.CATALOGUE_KEY, lesCourseCatalogues);
            log.info("从数据库中获取课程目录");
        }
        return buildTree(lesCourseCatalogues, 0L);
    }

    /**
     * 构建树形结构
     *
     * @param lesCourseCatalogues 课程目录
     * @return 课程目录
     */
    public List<LesCourseCatalogue> buildTree(List<LesCourseCatalogue> lesCourseCatalogues, Long pid) {

        List<LesCourseCatalogue> result = new ArrayList<>();

        for (LesCourseCatalogue lesCourseCatalogue : lesCourseCatalogues) {
            if (lesCourseCatalogue.getParentCatalogueId().equals(pid)) {
                List<LesCourseCatalogue> children = buildTree(lesCourseCatalogues, lesCourseCatalogue.getId());
                lesCourseCatalogue.setChildren(children);
                result.add(lesCourseCatalogue);
            }
        }
        return result;
    }
    /**
     * 新增课程目录
     *
     * @param lesCourseCatalogue 课程目录
     * @return 结果
     */
    @Override
    public int insertLesCourseCatalogue(LesCourseCatalogue lesCourseCatalogue) {
        lesCourseCatalogue.setCreateTime(DateUtils.getNowDate());
        return lesCourseCatalogueMapper.insertLesCourseCatalogue(lesCourseCatalogue);
    }

    /**
     * 修改课程目录
     *
     * @param lesCourseCatalogue 课程目录
     * @return 结果
     */
    @Override
    public int updateLesCourseCatalogue(LesCourseCatalogue lesCourseCatalogue) {
        lesCourseCatalogue.setUpdateTime(DateUtils.getNowDate());
        return lesCourseCatalogueMapper.updateLesCourseCatalogue(lesCourseCatalogue);
    }

    /**
     * 批量删除课程目录
     *
     * @param ids 需要删除的课程目录主键
     * @return 结果
     */
    @Override
    public int deleteLesCourseCatalogueByIds(Long[] ids) {
        return lesCourseCatalogueMapper.deleteLesCourseCatalogueByIds(ids);
    }

    /**
     * 删除课程目录信息
     *
     * @param id 课程目录主键
     * @return 结果
     */
    @Override
    public int deleteLesCourseCatalogueById(Long id) {
        return lesCourseCatalogueMapper.deleteLesCourseCatalogueById(id);
    }

    /**
     * 目录批量新增
     *
     * @param lesCourseCatalogueList 课程目录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertLesCourseCatalogueList(List<LesCourseCatalogue> lesCourseCatalogueList) {
        for (LesCourseCatalogue lesCourseCatalogue : lesCourseCatalogueList) {
            lesCourseCatalogueMapper.insertLesCourseCatalogue(lesCourseCatalogue);
        }
        return lesCourseCatalogueList.size();
    }

    /**
     * 获取章节下小节
     *
     * @param id 章节id
     * @return 结果
     */
    @Override
    public List<LesCourseCatalogue> selectSubsectionList(Long id) {
        LambdaQueryWrapper<LesCourseCatalogue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LesCourseCatalogue::getParentCatalogueId, id);
        queryWrapper.orderByAsc(LesCourseCatalogue::getCIndex);
        return lesCourseCatalogueMapper.selectList(queryWrapper);
    }

    /**
     * 获取全部目录
     *
     * @param courseId 课程id
     * @return 结果
     */
    @Override
    public List<LesAllCatalogueVo> selectAllCatalogueList(Long courseId) {
        // 记录日志，开始获取全部目录
        log.info("获取全部目录:{}", courseId);

        // 创建LambdaQueryWrapper对象，用于查询章节
        LambdaQueryWrapper<LesCourseCatalogue> chapterQueryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件：课程ID等于传入的courseId
        chapterQueryWrapper.eq(LesCourseCatalogue::getCourseId, courseId);
        // 设置查询条件：类型为章节
        chapterQueryWrapper.eq(LesCourseCatalogue::getType, Constants.CATEGORY_CHAPTER);
        // 设置排序条件：按照章节索引升序排列
        chapterQueryWrapper.orderByAsc(LesCourseCatalogue::getCIndex);
        // 执行查询，获取章节列表
        List<LesCourseCatalogue> chapters = lesCourseCatalogueMapper.selectList(chapterQueryWrapper);

        // 创建LambdaQueryWrapper对象，用于查询小节
        LambdaQueryWrapper<LesCourseCatalogue> subsectionQueryWrapper = new LambdaQueryWrapper<>();
        // 设置查询条件：课程ID等于传入的courseId
        subsectionQueryWrapper.eq(LesCourseCatalogue::getCourseId, courseId);
        // 设置查询条件：类型不为章节且不为测试
        subsectionQueryWrapper.ne(LesCourseCatalogue::getType, Constants.CATEGORY_CHAPTER);
        // 设置排序条件：按照小节索引升序排列
        subsectionQueryWrapper.orderByAsc(LesCourseCatalogue::getCIndex);
        // 执行查询，获取小节列表
        List<LesCourseCatalogue> subsections = lesCourseCatalogueMapper.selectList(subsectionQueryWrapper);
        List<SectionVO> sectionVoList = new ArrayList<>();
        for (LesCourseCatalogue subsection : subsections) {
            SectionVO sectionVO = new SectionVO();
            BeanUtils.copyProperties(subsection, sectionVO);
            sectionVoList.add(sectionVO);
        }
        List<Long> chapterIds = sectionVoList.stream().map(SectionVO::getId).collect(Collectors.toList());
        LambdaQueryWrapper<ExaQuestionBiz> questionQueryWrapper = new LambdaQueryWrapper<>();
        questionQueryWrapper.in(ExaQuestionBiz::getBizId, chapterIds);
        List<ExaQuestionBiz> questionList = exaQuestionBizMapper.selectList(questionQueryWrapper);
        Map<Long, List<ExaQuestionBiz>> questionMap = questionList.stream().collect(Collectors.groupingBy(ExaQuestionBiz::getBizId));
        for (SectionVO section : sectionVoList) {
            List<ExaQuestionBiz> questions = questionMap.get(section.getId());
            if (questions != null) {
                section.setSubjectNum(questions.size());
                section.setHasTest(true);
            } else {
                section.setHasTest(false);
            }
        }
        // 将小节列表按父目录ID进行分组
        Map<Long, List<SectionVO>> subsectionMap = sectionVoList.stream()
                .collect(Collectors.groupingBy(SectionVO::getParentCatalogueId));
        // 创建结果列表
        List<LesAllCatalogueVo> lesAllCatalogueVoList = new ArrayList<>();
        // 遍历章节列表
        for (LesCourseCatalogue chapter : chapters) {
            // 创建LesAllCatalogueVo对象
            LesAllCatalogueVo lesAllCatalogueVo = new LesAllCatalogueVo();
            // 将章节属性复制到LesAllCatalogueVo对象
            BeanUtils.copyProperties(chapter, lesAllCatalogueVo);
            // 获取当前章节ID对应的小节列表，若不存在则使用空列表
            List<SectionVO> subsectionList = subsectionMap.getOrDefault(chapter.getId(), new ArrayList<>());
            // 设置小节列表到LesAllCatalogueVo对象
            lesAllCatalogueVo.setChildren(subsectionList);
            // 将LesAllCatalogueVo对象添加到结果列表中
            lesAllCatalogueVoList.add(lesAllCatalogueVo);
        }
        // 返回结果列表
        return lesAllCatalogueVoList;
    }


    /**
     * 批量新增章节及其小节
     *
     * @param lesCourseCatalogueList 课程目录
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertAllCatalogueList(List<LesCatalogueListDto> lesCourseCatalogueList) {
        int insertedRecordCount = 0;
        int sum=0;
        for (LesCatalogueListDto dto : lesCourseCatalogueList) {
            LesCourseCatalogue chapter = dto.getChapter();
            if (chapter.getId() == null) {
                insertedRecordCount += lesCourseCatalogueMapper.insert(chapter);
            }
            for (LesCourseCatalogue subsection : dto.getChildren()) {
                if (subsection != null) {
                    subsection.setParentCatalogueId(chapter.getId());
                    insertedRecordCount += lesCourseCatalogueMapper.insert(subsection);
                    sum+=0;
                }
            }
        }
        LesCourse lesCourse = lesCourseMapper.selectById(lesCourseCatalogueList.get(0).getChapter().getCourseId());
        lesCourse.setSectionNum(lesCourse.getSectionNum()+sum);
        lesCourse.setUpdateTime(DateUtils.getNowDate());
        lesCourse.setPublishTimes(lesCourse.getPublishTimes() + 1);
        lesCourseMapper.updateById(lesCourse);
        return insertedRecordCount;
    }

    /**
     * 获取全部章节
     *
     * @param id 课程id
     * @return 结果
     */
    @Override
    public List<LesCourseCatalogue> selectCourseChapterList(Long id) {
        LambdaQueryWrapper<LesCourseCatalogue> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(LesCourseCatalogue::getCourseId, id);
        queryWrapper.eq(LesCourseCatalogue::getType, 1);
        queryWrapper.orderByAsc(LesCourseCatalogue::getCIndex);
        return lesCourseCatalogueMapper.selectList(queryWrapper);
    }


}
